import { useEffect, useMemo, useState } from 'react'
import { View, Text, ScrollView, Image, Textarea } from '@tarojs/components'
import Taro from '@tarojs/taro'
import './index.scss'
import userAvatar from '../../../resource/user.png'
import serviceAvatar from '../../../resource/nojiz.png'
import { ArrowLeft } from '@nutui/icons-react'
import { NavBar } from '@nutui/nutui-react-taro'

type MessageType = 'text' | 'image'
type MessageRole = 'user' | 'service'

interface ChatMessage {
  id: string
  type: MessageType
  role: MessageRole
  content: string
  timestamp: number
}

const createId = () => `${Date.now()}_${Math.random().toString(36).slice(2, 8)}`

const CustomerServiceChat = () => {
  const [inputValue, setInputValue] = useState('')
  const [messages, setMessages] = useState<ChatMessage[]>(() => ([
    {
      id: createId(),
      type: 'text',
      role: 'service',
      content: '您好，这里是家伟记账客服，很高兴为您服务~',
      timestamp: Date.now()
    }
  ]))

  const lastMessageId = useMemo(() => (messages.length ? messages[messages.length - 1].id : ''), [messages])

  useEffect(() => {
    if (!lastMessageId) return
    // 让 ScrollView 滚动到最后一条消息
    // 依赖 scrollIntoView 属性
  }, [lastMessageId])

  const formatTime = (ts: number) => {
    const date = new Date(ts)
    return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
  }

  const addMessage = (message: ChatMessage) => {
    setMessages(prev => [...prev, message])
  }

  const handleSendText = () => {
    const value = inputValue.trim()
    if (!value) {
      Taro.showToast({ title: '请输入内容', icon: 'none' })
      return
    }

    addMessage({
      id: createId(),
      type: 'text',
      role: 'user',
      content: value,
      timestamp: Date.now()
    })
    setInputValue('')

    // 模拟客服回复
    setTimeout(() => {
      addMessage({
        id: createId(),
        type: 'text',
        role: 'service',
        content: '我们已经收到您的消息，稍后会有专人与您联系。',
        timestamp: Date.now()
      })
    }, 1200)
  }

  const handleChooseImage = async (source: 'album' | 'camera') => {
    try {
      const res = await Taro.chooseImage({
        count: 1,
        sourceType: source === 'album' ? ['album'] : ['camera']
      })
      if (!res.tempFilePaths?.length) return

      const path = res.tempFilePaths[0]
      addMessage({
        id: createId(),
        type: 'image',
        role: 'user',
        content: path,
        timestamp: Date.now()
      })

      // 模拟客服确认
      setTimeout(() => {
        addMessage({
          id: createId(),
          type: 'text',
          role: 'service',
          content: '图片已收到，我们会尽快处理。',
          timestamp: Date.now()
        })
      }, 1500)
    } catch (error) {
      Taro.showToast({ title: '操作失败，请重试', icon: 'none' })
    }
  }

  const handleMoreAction = () => {
    Taro.showActionSheet({
      itemList: ['从相册选择', '拍照']
    }).then(res => {
      if (res.tapIndex === 0) {
        handleChooseImage('album')
      } else if (res.tapIndex === 1) {
        handleChooseImage('camera')
      }
    }).catch(() => { })
  }

  const handlePreviewImage = (url: string) => {
    const imageUrls = messages.filter(msg => msg.type === 'image').map(msg => msg.content)
    Taro.previewImage({ current: url, urls: imageUrls })
  }

  return (
    <View className="chat-page">
      <NavBar
        back={
          <>
            <ArrowLeft />
            返回
          </>
        }

        onBackClick={(e) => Taro.switchTab({ url: 'pages/user/index' })  }
      >
        联系客服
      </NavBar>
      <ScrollView
        className="chat-scroll"
        scrollY
        scrollIntoView={lastMessageId ? `msg-${lastMessageId}` : ''}
      >
        <View className="chat-tips">
          <Text>客服在线时间：09:00 - 22:00，如遇紧急问题请拨打热线 400-123-4567</Text>
        </View>

        {messages.map(message => (
          <View
            key={message.id}
            id={`msg-${message.id}`}
            className={`chat-item ${message.role === 'user' ? 'item-user' : 'item-service'}`}
          >
            <Image
              className="avatar"
              src={message.role === 'user' ? userAvatar : serviceAvatar}
              mode="aspectFill"
            />
            <View className={`chat-bubble ${message.role === 'user' ? 'bubble-user' : 'bubble-service'}`}>
              <View className="bubble-meta">
                <Text className="bubble-role">{message.role === 'user' ? '我' : '客服'}</Text>
                <Text className="bubble-time">{formatTime(message.timestamp)}</Text>
              </View>
              {message.type === 'text' ? (
                <View className="bubble-content">{message.content}</View>
              ) : (
                <Image
                  className="bubble-image"
                  src={message.content}
                  mode="aspectFill"
                  onClick={() => handlePreviewImage(message.content)}
                />
              )}
            </View>
          </View>
        ))}
      </ScrollView>

      <View className="chat-input-bar">
        <Textarea
          className="input-textarea"
          value={inputValue}
          maxlength={-1}
          autoHeight
          placeholder="请输入要咨询的问题..."
          onInput={(e) => setInputValue(e.detail.value)}
        // onConfirm={handleSendText}
        />
        <View className="input-actions">
          <View className="action-btn" onClick={handleMoreAction}>
            <Text className="action-plus">+</Text>
          </View>
          <View className="send-btn" onClick={handleSendText}>
            <Text>发送</Text>
          </View>
        </View>
      </View>
    </View>
  )
}

export default CustomerServiceChat

